package org.xenon.vote.service;

import org.springframework.stereotype.Service;
import org.xenon.vote.config.MailConfig;
import org.xenon.vote.dao.imp.RecDao;
import org.xenon.vote.dao.imp.UserDao;
import org.xenon.vote.model.pojo.po.Rec;
import org.xenon.vote.model.pojo.po.User;
import org.xenon.vote.model.pojo.vo.Mail;
import org.xenon.vote.util.CharUtil;
import org.xenon.vote.util.mail.MailSender;

import java.util.Date;

@Service
public class MailService {
    private final MailConfig mailConfig;
    private final RecDao recDao;
    private final UserDao userDao;
    private String title = "\u8FD9\u662F\u5BC6\u7801\u91CD\u7F6E\u90AE\u4EF6";
    private String body = "\u5982\u679C\u60A8\u521A\u624D\u5728\u6295\u7968\u7CFB\u7EDF\u7533\u8BF7\u4E86\u91CD\u7F6E\u5BC6\u7801, \u5219\u8BF7\u8BBF\u95EE\u4E0B\u65B9\u7684\u94FE\u63A5\u5B8C\u6210\u9A8C\u8BC1. \u5982\u679C\u60A8\u6CA1\u6709\u505A\u8FC7\u8BE5\u64CD\u4F5C, \u5219\u8BF7\u60A8\u5FFD\u7565\u90AE\u4EF6.";
    private String url = "https://wing.xiyan.asia/user/check/";
    private final MailSender mailSender;

    public MailService(MailConfig mailConfig, RecDao recDao, UserDao userDao, MailSender mailSender) {
        this.mailConfig = mailConfig;
        this.recDao = recDao;
        this.userDao = userDao;
        this.mailSender = mailSender;
    }

    /**
     * 发送密码重置验证邮件
     * @param mail 收件人账号
     * @return 验证口令
     */
    @SuppressWarnings("UnusedReturnValue")
    public String resetPasswd(String mail, String passwd, int age){
        recDao.delAll(mail);
        String token = CharUtil.getRandomString(24);
        recDao.add(new Rec(token, mail, passwd, new Date(), age));
        Mail msg = new Mail(mail, title, body + url + token);
        mailSender.taskQQ(mailConfig, msg);
        return token;
    }

    public boolean checkRecToken(String token){
        Rec rec = recDao.get(token);
        if (
                rec == null ||
                ((System.currentTimeMillis() - rec.getBirth().getTime())/1000 > rec.getAge()*1000)
        )
            return false;
        recDao.delAll(rec.getMail());
        User user = userDao.get(rec.getMail());
        user.setPassword(rec.getPasswd());
        userDao.edit(user);
        return true;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
